//
//  ZHDBManager.m
//  VehicleInsuranceSupport
//
//  Created by TangBin on 2019/11/4.
//  Copyright © 2019 TangBin. All rights reserved.
//

#import "ZHDBManager.h"

@implementation ZHDBManager

+ (NSString *)dbDataPath
{
    return dataBasePath;
}

/// App启动的时候初始化
+ (void)setupDBSettins
{
    debugLog(@"dbpath=%@", [self dbDataPath]);
    if (![NSFileManager isPathFileExit:[self dbDataPath]])
    {// 数据库不存在
        [self createTables];
        return;
    }
    
    NSString *sqliteVersion = [self queryDBVersion];
    if (![sqliteVersion isEqualToString:MY_SQLITE_VERSION] && [sqliteVersion floatValue] >= LATEST_REPLACEDATA_SQLITE_VERSION)
    {// 数据库版本号设置版本不同 && 数据库版本大于LATEST_REPLACEDATA_SQLITE_VERSION
        [self updateDBVersion:sqliteVersion];
    }
}

/// 更新数据库
+ (void)updateDB
{
    if (![NSFileManager isPathFileExit:[self dbDataPath]])
    {// 数据库不存在
        return;
    }
    
    NSString *sqliteVersion = [self queryDBVersion];
    if (![sqliteVersion isEqualToString:MY_SQLITE_VERSION])
    {
        [self updateDBVersion:sqliteVersion];
    }
}

+ (void)updateDBVersion:(NSString *)sqliteVersion
{
    [self closeDB];
    NSRange range = [sqliteVersion rangeOfString:@"."];
    if (range.location != NSNotFound)
    {
        NSString *versionStr = [sqliteVersion substringToIndex:range.location];
        if ([versionStr integerValue] < 2)
        {
            BOOL resultFlag = [[NSFileManager defaultManager] removeItemAtPath:[self dbDataPath] error:nil];
            if (resultFlag)
            {
                [self createTables];
            }
        }
    }
    else
    {
        [self updateDBTable:MY_SQLITE_VERSION oldVersion:sqliteVersion];
    }
}

/// 数据库是否需要同步更新
+ (BOOL)isSyncUpdateDB
{
    if ([NSFileManager isPathFileExit:[self dbDataPath]])
    {// 数据库存在
        NSString *sqliteVersion = [self queryDBVersion];
        if (![sqliteVersion isEqualToString:MY_SQLITE_VERSION] && [sqliteVersion floatValue] < LATEST_REPLACEDATA_SQLITE_VERSION)
        {// 表中存储的版本号跟最新版本号比较，不相同 && 数据库版本号小于这个
            return YES;
        }
    }
    return NO;
}

+ (FMDatabaseQueue *)getDBQueue
{
    return [ZHDBHelper databaseQueue];
}

+ (void)closeDB
{
    [[ZHDBHelper databaseQueue] close];
}

+ (void)createTables
{
    [ZHDBHelper createTable:CREATE_VERSION_TABLE tableName:T_DB_VERSION];
    
    // 课件学习
//    [ZHDBHelper createTable:CREATE_COURSEWARE_LEARN_TABLE tableName:T_DB_COURSEWARE_LEARN];
    [ZHDBHelper createTable:CREATE_PUSH_CIRCLE_TABLE tableName:T_DB_PUSH_CIRCLE_TABLE];
    
    
    // 新增的数据库表或者字段
    [self updateDBTable:MY_SQLITE_VERSION oldVersion:ORIGIN_SQLITE_VERSION];
}

/// 根据数据库版本号更新数据库(修改表结构、新增表)
/// @param sqlVersion 新版本号
/// @param oldVersion 旧版本号
+ (void)updateDBTable:(NSString *)sqlVersion oldVersion:(NSString *)oldVersion
{
    NSUInteger versionNum = [sqlVersion integerValue];
    NSUInteger oldVersionNum = [oldVersion integerValue];
    
    for (NSUInteger i=oldVersionNum+1; i<versionNum+1; i++)
    {
        switch (i)
        {
            case 3:
            {
//                [ZHDBHelper alterTableData:nil tableName:nil];
//                [ZHDBHelper createTable:nil tableName:nil];
            } break;
                
            default:
                break;
        }
    }
    
    
    // 设置数据库版本号
    [self setDBVersion:MY_SQLITE_VERSION];
    
}

+ (NSString *)queryDBVersion
{
    __block NSString *version = @"0";
    NSString *sql = [NSString stringWithFormat:@"select * from %@;", T_DB_VERSION];
    [ZHDBHelper querySql:sql resultSetBlock:^(FMResultSet * _Nonnull rs) {
        while ([rs next])
        {
            version = [rs stringForColumn:@"VersionValue"];
        }
    }];
    return version;
}

+ (void)setDBVersion:(NSString *)version
{
    NSString *sql = [NSString stringWithFormat:@"INSERT INTO %@ (VersionValue) VALUES ('%@')",T_DB_VERSION,version];
    [ZHDBHelper updateExecuteSql:sql];
}

@end



























